package jsyf.oa.service.system;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.system.RightDao;
import jsyf.oa.dao.system.RightOpDao;
import jsyf.oa.dao.system.UserDao;
import jsyf.oa.entity.system.RightEntity;
import jsyf.oa.facade.system.RightFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class RightService implements RightFacade {


    //菜单dao
    @Autowired
    private RightDao dao;

    @Autowired
    private UserDao userDao;
    @Autowired
    private RightOpDao rightOpDao;

    @Override
    public String save(String jsonData) {
        RightEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), RightEntity.class);
        if (StringUtils.isEmpty(entity.getId()) || "0".equals(entity.getId())) {
            dao.add(entity);
        } else {
            RightEntity oldEntity = dao.getEntityById(entity.getId());
            oldEntity.setName(entity.getName());
            oldEntity.setUrl(entity.getUrl());
            oldEntity.setDescription(entity.getDescription());
            oldEntity.setDefaultFlag(entity.getDefaultFlag());
            oldEntity.setRightType(entity.getRightType());
            oldEntity.setImageUrl(entity.getImageUrl());
            oldEntity.setAppFlag(entity.getAppFlag());
            oldEntity.setAppImageUrl(entity.getAppImageUrl());
            if (entity.getBloom() != null) {
                oldEntity.setBloom(entity.getBloom());
            }
            dao.update(oldEntity);
        }
        return entity.getId();
    }

    @Override
    public Boolean sort(String rightIds) {
        return dao.sort(rightIds);
    }

    @Override
    public JSONObject getById(String id) {
        return dao.getJSONById(id);
    }


    public List<JSONObject> getTreeNodes() {
        List<JSONObject> nodeList = new ArrayList<>();

        JSONObject nodeRoot = new JSONObject();
        nodeRoot.put("id", "0");
        nodeRoot.put("pId", "-1");
        nodeRoot.put("name", "系统菜单");
        nodeRoot.put("type", "root");
        nodeRoot.put("dataId", "0");
        nodeRoot.put("isParent", true);
        nodeRoot.put("open", true);
        nodeList.add(nodeRoot);

        List<JSONObject> list = dao.getJSONListByCondition(" ORDER BY SORT_NO", new Object[]{});
        for (int i = 0; i < list.size(); i++) {
            JSONObject node = list.get(i);
            if (StringUtils.isEmpty(node.getString("parentId")) || "0".equals(node.getString("parentId"))) {
                node.put("pId", "0");
                node.put("type", "rightFolder");
            } else {
                node.put("pId", node.getString("parentId"));
                node.put("type", "right");
            }

            node.put("dataId", node.getString("id"));
            nodeList.add(node);
        }

        List<JSONObject> rightOpList = rightOpDao.getJSONListByCondition("", new Object[]{});
        for (int i = 0; i < rightOpList.size(); i++) {
            JSONObject node = rightOpList.get(i);
            node.put("pId", node.getString("rightId"));
            node.put("type", "rightOp");
            nodeList.add(node);
        }
        return nodeList;
    }

    @Override
    public Boolean removeById(String id) {
        return dao.removeById(id) > 0;
    }

    @Override
    public List<JSONObject> getMenuByUserId(String jsonParams) {
        JSONObject jsonParam = FastJsonConvert.convertJSONToObject(jsonParams, JSONObject.class);
        String userId = jsonParam.getString("userId");
        String rightType = jsonParam.getString("rightType");
        JSONObject results = userDao.getViewJSONById(userId);
        String companyBloom = results.getString("companyBloom");
        StringBuffer sql = new StringBuffer();
        if ("0".equals(companyBloom)) {
            if (userDao.isSuperUser(userId)) {
                return dao.getJSONListByCondition(" AND RIGHT_TYPE =?" +
                        " ORDER BY SORT_NO ", new Object[]{rightType});
            } else {
                sql.append(" AND ");
                sql.append(" ID IN(SELECT RIGHT_ID FROM T_SYS_USER_2_RIGHT WHERE USER_ID = ?) ");
                sql.append(" AND RIGHT_TYPE =? ");
                sql.append(" OR ");
                sql.append(" ID IN(SELECT RIGHT_ID FROM T_SYS_ROLE_NAME_2_RIGHT WHERE ");
                sql.append("       ROLE_NAME_ID IN(SELECT roleNameId FROM V_SYS_USER_2_ROLE WHERE userId = ?) ");
                sql.append("       OR ");
                sql.append("       ROLE_NAME_ID IN(SELECT ROLE_NAME_ID FROM T_SYS_ROLE WHERE ID IN(SELECT ROLE_ID FROM T_SYS_USER WHERE ID = ?)) ");
                sql.append("      )");
                sql.append(" AND RIGHT_TYPE =? ");
                sql.append(" OR DEFAULT_FLAG = 1 ");
                sql.append(" AND RIGHT_TYPE =? ");
                sql.append(" ORDER BY SORT_NO ");
                return dao.getJSONListByCondition(sql.toString(), new Object[]{userId, rightType, userId, userId, rightType, rightType});
            }
        } else {
            sql.append(" AND BLOOM=1 ");
            sql.append(" AND ( ");
            sql.append(" ID IN(SELECT RIGHT_ID FROM T_SYS_USER_2_RIGHT WHERE USER_ID = ?) ");
            sql.append(" AND RIGHT_TYPE =? ");
            sql.append(" OR ");
            sql.append(" ID IN(SELECT RIGHT_ID FROM T_SYS_ROLE_NAME_2_RIGHT WHERE ");
            sql.append("       ROLE_NAME_ID IN(SELECT roleNameId FROM V_SYS_USER_2_ROLE WHERE userId = ?) ");
            sql.append("       OR ");
            sql.append("       ROLE_NAME_ID IN(SELECT ROLE_NAME_ID FROM T_SYS_ROLE WHERE ID IN(SELECT ROLE_ID FROM T_SYS_USER WHERE ID = ?)) ");
            sql.append("      )");
            sql.append(" AND RIGHT_TYPE =? ");
            sql.append(" OR DEFAULT_FLAG = 1 )");
            sql.append(" AND RIGHT_TYPE =? ");
            sql.append(" ORDER BY SORT_NO ");
            return dao.getJSONListByCondition(sql.toString(), new Object[]{userId, rightType, userId, userId, rightType, rightType});
        }

    }

    @Override
    public List<JSONObject> getMenuByApp(String jsonParams) {
        JSONObject jsonParam = FastJsonConvert.convertJSONToObject(jsonParams, JSONObject.class);
        String userId = jsonParam.getString("userId");
        String appFlag = jsonParam.getString("appFlag");
        JSONObject results = userDao.getViewJSONById(userId);
        String companyBloom = results.getString("companyBloom");

        StringBuffer sql = new StringBuffer();
        if ("0".equals(companyBloom)) {
            if (userDao.isSuperUser(userId)) {
                return dao.getJSONListByCondition(" AND APP_FLAG =? ORDER BY SORT_NO ", new Object[]{appFlag});
            } else {
                sql.append(" AND ");
                sql.append(" ID IN(SELECT RIGHT_ID FROM T_SYS_USER_2_RIGHT WHERE USER_ID = ?) ");
                sql.append(" AND APP_FLAG =? ");
                sql.append(" OR ");
                sql.append(" ID IN(SELECT RIGHT_ID FROM T_SYS_ROLE_NAME_2_RIGHT WHERE ");
                sql.append("       ROLE_NAME_ID IN(SELECT roleNameId FROM V_SYS_USER_2_ROLE WHERE userId = ?) ");
                sql.append("       OR ");
                sql.append("       ROLE_NAME_ID IN(SELECT ROLE_NAME_ID FROM T_SYS_ROLE WHERE ID IN(SELECT ROLE_ID FROM T_SYS_USER WHERE ID = ?)) ");
                sql.append("      )");
                sql.append(" AND APP_FLAG =? ");
                sql.append(" OR DEFAULT_FLAG = 1 ");
                sql.append(" AND APP_FLAG =? ");
                sql.append(" ORDER BY SORT_NO ");
                return dao.getJSONListByCondition(sql.toString(), new Object[]{userId, appFlag, userId, userId, appFlag, appFlag});
            }
        } else {
            sql.append(" AND BLOOM=1 ");
            sql.append(" AND ( ");
            sql.append(" ID IN(SELECT RIGHT_ID FROM T_SYS_USER_2_RIGHT WHERE USER_ID = ?) ");
            sql.append(" AND APP_FLAG =? ");
            sql.append(" OR ");
            sql.append(" ID IN(SELECT RIGHT_ID FROM T_SYS_ROLE_NAME_2_RIGHT WHERE ");
            sql.append("       ROLE_NAME_ID IN(SELECT roleNameId FROM V_SYS_USER_2_ROLE WHERE userId = ?) ");
            sql.append("       OR ");
            sql.append("       ROLE_NAME_ID IN(SELECT ROLE_NAME_ID FROM T_SYS_ROLE WHERE ID IN(SELECT ROLE_ID FROM T_SYS_USER WHERE ID = ?)) ");
            sql.append("      )");
            sql.append(" AND APP_FLAG =? ");
            sql.append(" OR DEFAULT_FLAG = 1) ");
            sql.append(" AND APP_FLAG =? ");
            sql.append(" ORDER BY SORT_NO ");
            return dao.getJSONListByCondition(sql.toString(), new Object[]{userId, appFlag, userId, userId, appFlag, appFlag});
        }

    }

    @Override
    public List<JSONObject> getRoleRightByUserId(String userId) {
        StringBuffer sql = new StringBuffer();
        sql.append(" AND ");
        sql.append(" ID IN(SELECT RIGHT_ID FROM T_SYS_ROLE_NAME_2_RIGHT WHERE ");
        sql.append("       ROLE_NAME_ID IN(SELECT roleNameId FROM V_SYS_USER_2_ROLE WHERE userId = ?) ");
        sql.append("       OR ");
        sql.append("       ROLE_NAME_ID IN(SELECT ROLE_NAME_ID FROM T_SYS_ROLE WHERE ID IN(SELECT ROLE_ID FROM T_SYS_USER WHERE ID = ?)) ");
        sql.append("      )");
        return dao.getJSONListByCondition(sql.toString(), new Object[]{userId, userId});
    }
}
